﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Utilities
{
    /// <summary>
    ///XmlHelper 的摘要说明
    /// </summary>
    public class XmlHelper
    {
        /// <summary>
        /// 序列化任意对象（XML）
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>序列化后的 XML 字符串</returns>
        public static string SerializableObject(object obj)
        {
            XmlSerializer xml = new XmlSerializer(obj.GetType());
            MemoryStream ms = new MemoryStream();
            xml.Serialize(ms, obj);
            byte[] tmpBytes = ms.ToArray();
            ms.Close();
            return System.Text.Encoding.UTF8.GetString(tmpBytes);
        }
        /// <summary>
        /// 反序列化任意对象（XML）
        /// </summary>
        /// <param name="xmlString">XML字符串</param>
        /// <returns>反序列化后的对象</returns>
        public static T DeSerializeObject<T>(string xmlString)
        {
            byte[] tmpBytes = System.Text.Encoding.Default.GetBytes(xmlString);
            MemoryStream ms = new MemoryStream(tmpBytes);
            ms.Position = 0;
            XmlSerializer xml = new XmlSerializer(typeof(T));
            T obj = (T)xml.Deserialize(ms);
            ms.Close();
            return obj;
        }
    }
}
